package com.record.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ws.schild.jave.Encoder;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;
import ws.schild.jave.info.AudioInfo;
import ws.schild.jave.info.MultimediaInfo;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @projectName: ngsapitask-tp2.6
 * @package: com.elite.groovy.dev
 * @className: Qn_Dev
 * @author: LiJT
 * @description: TODO
 * @date: 2024-09-05 19:09
 * @version: 1.0
 */
public class RecordEncode {
    private static final Log log = LogFactory.getLog(RecordEncode.class);

    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, EncoderException {

        String amrFilePath = "D:\\Tomcats\\Apache-Tomcat-9.0.76\\webapps\\ROOT\\amr.amr";
        String wavFilePath = "D:\\Tomcats\\Apache-Tomcat-9.0.76\\webapps\\ROOT\\wav.wav";

        info(amrFilePath);

        audioEncode(amrFilePath,wavFilePath);
        info(wavFilePath);

    }

    /**
     * 获取音频文件的编码信息
     *
     * @param filePath
     * @throws EncoderException
     */
    private static void info(String filePath) throws EncoderException {
        File file = new File(filePath);
        MultimediaObject multimediaObject = new MultimediaObject(file);
        MultimediaInfo info = multimediaObject.getInfo();
        // 时长
        long duration = info.getDuration();
        String format = info.getFormat();
        // format:mov
        log.debug("AudioInfo format:" + format);

        AudioInfo audio = info.getAudio();
        // 它设置将在重新编码的音频流中使用的音频通道数（1 =单声道，2 =立体声）。如果未设置任何通道值，则编码器将选择默认值。
        int channels = audio.getChannels();
        // 它为新的重新编码的音频流设置比特率值。如果未设置比特率值，则编码器将选择默认值。
        // 该值应以每秒位数表示。例如，如果您想要128 kb / s的比特率，则应调用setBitRate（new Integer（128000））。
        int bitRate = audio.getBitRate();
        // 它为新的重新编码的音频流设置采样率。如果未设置采样率值，则编码器将选择默认值。该值应以赫兹表示。例如，如果您想要类似CD
        // 采样率、音频采样级别 16000 = 16KHz
        int samplingRate = audio.getSamplingRate();

        // 设置音频音量
        // 可以调用此方法来更改音频流的音量。值为256表示音量不变。因此，小于256的值表示音量减小，而大于256的值将增大音频流的音量。
        // setVolume(Integer volume)

        String decoder = audio.getDecoder();

        log.debug("AudioInfo 声音时长:毫秒" + duration);
        log.debug("AudioInfo 声道:" + channels);
        log.debug("AudioInfo bitRate:" + bitRate);
        log.debug("AudioInfo samplingRate 采样率、音频采样级别 16000 = 16KHz:" + samplingRate);
        log.debug("AudioInfo decoder:" + decoder);
    }
    /**
     * 音频格式转换
     * @param inputFormatPath
     * @param outputFormatPath
     * @return
     */
    public static boolean audioEncode(String inputFormatPath, String outputFormatPath) {
        String inputFormat =getSuffix(inputFormatPath);
        String outputFormat = getSuffix(outputFormatPath);
        log.debug("outputFormat:" + outputFormat);

        File source = new File(inputFormatPath);
        File target = new File(outputFormatPath);
        try {
            MultimediaObject multimediaObject = new MultimediaObject(source);
            // 获取音频文件的编码信息
            MultimediaInfo info = multimediaObject.getInfo();
            AudioInfo audioInfo = info.getAudio();
            log.debug("获取音频文件的编码信息format:" + info.getFormat());

            //设置音频属性
            AudioAttributes audio = new AudioAttributes();
            audio.setBitRate(16000);
            audio.setSamplingRate(8000);
            // audio.setChannels(audioInfo.getChannels());
            // 设置转码属性
            EncodingAttributes attrs = new EncodingAttributes();
            attrs.setInputFormat(inputFormat);
            attrs.setOutputFormat(outputFormat);
            attrs.setAudioAttributes(audio);
            // 音频转换格式类
            Encoder encoder = new Encoder();
            // 进行转换
            encoder.encode(new MultimediaObject(source), target, attrs);
            return true;
        } catch (IllegalArgumentException | EncoderException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取文件路径的.后缀
     * @param outputFormatPath
     * @return
     */
    private static String getSuffix(String outputFormatPath) {
        return outputFormatPath.substring(outputFormatPath.lastIndexOf(".") + 1);
    }


}
